import { isEmpty } from "@/utils"
import { GetanTableFilterProps, GetanTableFilterType, GetanTableProps } from "../types"

/**
 * 支持条件过滤
 */
export function useFilter(props: Ref<Partial<GetanTableProps>>) {
    /**
     * 默认过滤条件，不显示，不修改
     */
    const defaultFilterRef = computed(() => unref(props).defaultFilter ?? {})
    /**
     * 动态过滤条件
     */
    const conditionsRef = shallowRef<GetanTableFilterType[]>([])
    /**
     * 可设置过滤条件的字段
     */
    const filterColumns = ref<GetanTableFilterProps[]>([])
    /**
     * 设置查询条件
     */
    const getFilterParams = (params: Recordable) => {
        if (!isEmpty(defaultFilterRef.value)) {
            Object.keys(defaultFilterRef.value).forEach(k => (params[k] = defaultFilterRef.value[k]))
        }
        if (isEmpty(params.conditions)) {
            params.conditions = []
        }
        const conditions = params.conditions as GetanTableFilterType[]
        conditionsRef.value.forEach(v => conditions.push(v))
    }
    /**
     * 设置查询条件
     */
    const setFilterConditions = (conditions: GetanTableFilterType[]) => {
        conditionsRef.value = conditions
    }

    return { getFilterParams, filterColumns, setFilterConditions }
}
